package other.xsy.passlys;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.*;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import other.xsy.passlys.util.HCXObjectService;
import other.xsy.passlys.util.HcUtils;

import java.util.Objects;

/**
 * @Description 客户报备升降级审批通过: 调整客户业务类型
 * @Author 黎炎松
 * 2024-06-14 11:37
 */
public class CustomerRelevanceCompleteAfter implements ApprovalEvent {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "客户报备升降级审批通过: 调整客户业务类型 ==> ";

    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + "触发开始");
        logger.info("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId());
        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        upAccountEntityType(request.getDataId());
        return response;
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        CustomerRelevanceCompleteAfter customerRelevanceCompleteAfter = new CustomerRelevanceCompleteAfter();
        //customerRelevanceCompleteAfter.upAccountEntityType(3335302175119936L);
    }

    /**
     * 修改客户业务类型 customerRelevance__c
     * @param dataId
     */
    public void upAccountEntityType(Long dataId){
        try {
            CustomerRelevance__c customerRelevance = new CustomerRelevance__c();
            customerRelevance.setId(dataId);
            customerRelevance = hcxObjectService.get(customerRelevance);
            logger.info(LOGGER_MSG + "处理开始: " + customerRelevance);

            // 判断类型是 客户升降级
            Long entityType = customerRelevance.getEntityType();
            if (entityType != 3331014618389132L) {
                logger.debug(LOGGER_MSG + "当前类型不需要处理");
                return;
            }

            // 获取需要调整业务类型的 id
            Long entityTypeId = getEntityType(customerRelevance);
            logger.debug(LOGGER_MSG + "entityTypeId = " + entityTypeId);
            if (entityTypeId == null) {
                logger.error(LOGGER_MSG + "获取业务类型异常");
                return;
            }

            // 通过客户名称信息获取关联客户
            Long customerNameId = customerRelevance.getCustomerName__c();
            String sql = "select id,associatedCustomer__c from customerName__c where id = " + customerNameId;
            CustomerName__c customerName = hcxObjectService.queryOne(sql, CustomerName__c.class);
            if (customerName == null) {
                logger.error(LOGGER_MSG + "获取管理客户信息异常");
                return;
            }

            // 设置客户类型
            Long accountId = customerName.getAssociatedCustomer__c();
            Account account = new Account();
            account.setId(accountId);
            account.setEntityType(entityTypeId);
            Boolean update = hcxObjectService.update(account);
            if (!update) {
                logger.error(LOGGER_MSG + "修改客户类型异常");
                return;
            }

            logger.debug(LOGGER_MSG + "处理成功");
        } catch (Exception e) {
            logger.debug(LOGGER_MSG + "处理异常:" + e.getMessage());
        }
    }


    /**
     * 获取需要设置的 业务类型值 （存在单选字段 【升降机后客户类型】api名称）
     * @param customerRelevance
     * @return
     * @throws Exception
     */
    public Long getEntityType(CustomerRelevance__c customerRelevance) throws Exception {
        // 获取对象实体信息
        Long entityTypeId = null;
        JSONObject entityObj = HcUtils.getEntityDesc(customerRelevance.getApiKey());
        JSONObject entityData = entityObj.getJSONObject("data");
        JSONArray fieldArray = entityData.getJSONArray("fields");

        JSONObject field = null;
        for (Object o : fieldArray) {
            JSONObject obj = (JSONObject) o;
            if (Objects.equals(obj.getString("apiKey"), "customItem9__c")) {
                field = obj;
                break;
            }
        }

        // 获取下拉选项 匹配值
        if (field != null) {
            JSONArray selectitem = field.getJSONArray("selectitem");
            for (Object selItem : selectitem) {
                JSONObject sel = (JSONObject) selItem;
                if (Objects.equals(sel.getInteger("value"), customerRelevance.getCustomItem9__c())) {
                    entityTypeId = sel.getLong("apiKey");
                    break;
                }
            }
        }

        return entityTypeId;
    }



}
